import {computed, CSSProperties, defineComponent,Transition,ref, inject, toRef} from "vue"
import styles from '../styles/thumbTsx.module.scss'
import {GAP,BAR_MAP,scrollbarContextKey} from "./constants"
import {isClient,useEventListener} from "@vueuse/core"
export default defineComponent({
    props:{
        size:{
            type:Number,
            default:0
        },
        move:{
            type:Number,
            default:0
        },
        ratio:{
            type:Number,
        },
        vertical:{
            type:Boolean,
            default:false
        }
    },
    setup(props,{slots}){
        let cursorDown = false //是否点击了thumb
        let instance = ref()//滚动条bar实例
        let thumb = ref()//滚动条实例

        const scrollbar = inject(scrollbarContextKey)

        let bar = computed(()=>BAR_MAP[props.vertical?"vertical":"horizontal"])//获取滚动条相应的变量
        const thumbState = ref<Record<string,number>>({})


        let  originalOnSelectStart :|((this:GlobalEventHandlers,ev:Event)=>any)|null = isClient?
document.onselectstart:null

        const offsetRatio = computed(()=>{
            if(!instance.value||!props.ratio)return 1
           return instance.value![bar.value.offset]**2/
            props.ratio/
            scrollbar!.wrapElement.value![bar.value.scrollsize]/
            thumb.value![bar.value.offset]
        }
        )

        // 是否显示滚动条
        let visible = ref<boolean>(false)
        
        // 动态样式
        let style = computed(()=>{
                let styles:CSSProperties={}
                if(props.vertical){
                    styles.transform = `translateY(${props.move}%)`
                    styles.height = `${props.size}px`
                   }else{
                    styles.transform = `translateX(${props.move}%)`
                    styles.width = `${props.size}px`
                   }
                //    console.log(props.move,"我方解封")

                return styles
        })

        //drag拉拽滚动条 触发事件
        const clickThumbHandler =(e:any)=>{
        //    console.log(e.currentTarget,"current")
            e.stopPropagation()
            if(e.ctrlKey || [1,2].includes(e.button))return
            // 真正的触发的开始
            startDrag(e)
            const el = e.currentTarget  as  any
            if(!el) return
            thumbState.value[bar.value.axis] = el[bar.value.offset]-
                (e[bar.value.client]-el.getBoundingClientRect?.()[bar.value.direction])
        
        }
        // 真正的触发的开始
        const startDrag =(e:MouseEvent)=>{
           
            e.stopImmediatePropagation()
            cursorDown = true
            document.addEventListener("mousemove",mouseMoveDocumentHandler)
            document.addEventListener("mouseup",mouseUpDocumentHandler)
            originalOnSelectStart =document.onselectstart
            document.onselectstart = ()=>false
        }

        // 鼠标拖动事件
        const mouseMoveDocumentHandler = (e:any)=>{
         
           
            if (!instance.value || !thumb.value) return
            if(!cursorDown) return
          
            const prevPage = thumbState.value[bar.value.axis]
        
            if(!prevPage)return
           
            const offset = 
            (instance.value?.getBoundingClientRect()[bar.value.direction] 
            - e[bar.value.client])*-1
             
            const thumbClickPosition = thumb.value[bar.value.offset] - prevPage
            const thumbPositionPercentage = 
            ((offset-thumbClickPosition)*100*offsetRatio.value)/
            instance.value[bar.value.offset]
          
            scrollbar!.wrapElement.value[bar.value.scroll]=
            (thumbPositionPercentage*scrollbar?.wrapElement.value[bar.value.scrollsize])/100
            
        
        }

        // 结束鼠标滚动事件
      let  mouseUpDocumentHandler = (e:MouseEvent)=>{
            cursorDown = false
            thumbState.value[bar.value.axis] = 0
            document.removeEventListener("mousemove",mouseMoveDocumentHandler)
            document.removeEventListener("mouseup",mouseUpDocumentHandler)
            restoreOnselectstart()
            if(cursorDown) visible.value = false
      }


        //   点击滚动条触发页面和滚动块的移动
        const clickTrackHandler = (e:any)=>{
           if(!thumb.value || !instance.value)return
        //    console.log("fesfes")
           const offset = Math.abs((e.target).getBoundingClientRect()
           [bar.value.direction]-e[bar.value.client])
            
           const thumbHalf = thumb.value[bar.value.offset]/2

           const thumbPositionPercentage = (
            (offset-thumbHalf)*100*offsetRatio.value/
            instance.value[bar.value.offset]
           )
           scrollbar!.wrapElement.value[bar.value.scroll]=
           (thumbPositionPercentage*scrollbar?.wrapElement.value[bar.value.scrollsize])/100
           

        }

        // 鼠标在滚动条上时,显示滚动条
        const mouseMoveScrollbarHandler = ()=>{
            visible.value = !! props.size
        }

        //鼠标离开滚动条是，隐藏滚动条
        const mouseLeaveScrollbarHandler = ()=>{
            visible.value = false
        }

        const restoreOnselectstart = ()=>{
            if(document.onselectstart !==originalOnSelectStart)
            document.onselectstart = originalOnSelectStart
        }

        useEventListener(toRef(scrollbar!,"scrollbarElement"),"mousemove",mouseMoveScrollbarHandler)
        useEventListener(toRef(scrollbar!,"scrollbarElement"),"mouseleave",mouseLeaveScrollbarHandler)

        return ()=>(
            <>
               <Transition name="fade" mode="out-in">
                    <div v-show={visible.value} class={[props.vertical?styles.vertical:styles.horizontal]} ref={instance} onMousedown={(e)=>clickTrackHandler(e)}>
                        <div ref={thumb} class={styles.thumb} style={style.value} onMousedown={(e:MouseEvent)=>clickThumbHandler(e)}>
                            
                        </div>
                    </div>
               </Transition>
            </>
        )

    }

})